﻿var express = require('express');
var router = express.Router();
var db = require('../db/db.js');
var config = require('../config');
var moment = require("moment");
var jwt = require('jsonwebtoken');
var crypto = require("crypto");
var NodeRSA = require('node-rsa');
var request = require("request");
var fs = require('fs');
var qs = require('qs');
var path = require('path');
var uuid = require('uuid');
const cache = require('memory-cache')
var http = require('http');
var log = require('../util/logger.js');
var sms = require("../util/sms");
var myutil = require("../util/util");
var wx_applets = require("../util/wx_applets.js");
var xml2js = require('xml2js');
var builder = new xml2js.Builder();
var parser = new xml2js.Parser();
var ip = require('ip');

var users_model = require("../model/users");

// var API = require('wechat-api');
// var wxgzhapi = new API(config.wxgzh.appid, config.wxgzh.secret);

var goods_model = require("../model/yoshop_goods");
var goods_spec_model = require("../model/yoshop_goods_spec");


//获取微信小程序openid
router.post("/gettoken", function (req, res) {


    console.log("sss", req.body);

    var req_params = {
        "appid": config.wx.appid,
        "secret": config.wx.secret,
        "js_code": req.body.code,
        "grant_type": 'authorization_code'
    }
    var content = qs.stringify(req_params);
    console.log(content);
    var url = "https://api.weixin.qq.com/sns/jscode2session?" + content;

    request({ url: url, method: 'GET' }, async function (error, response, body) {
        console.log('error:', error); // Print the error if one occurred
        console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
        console.log('body:', body);
        if (!error && response.statusCode == 200) {

            // {"session_key":"IVvCU8KWO09WuLevVRDe8A==","openid":"oni5U5fphCD7JDDC7C0yqJGr8_No"}
            var json = JSON.parse(body);
            var openid = json.openid;
            console.log("openid", openid);
            var user = await users_model.getinfo("open_id='" + openid + "'");
            if (user.length == 0) {
                var data = {};
                data.open_id = openid;
                data.nickname = JSON.parse(req.body.user_info).nickName;
                data.avatarurl = JSON.parse(req.body.user_info).avatarUrl;
                data.gender = JSON.parse(req.body.user_info).gender;

                var obj = await users_model.add(data);
                if (obj.code == 200) {

                    let content = { userid: obj.msg.insertId }; // 要生成token的主题信息
                    let secretOrPrivateKey = config.token.secretOrPrivateKey; // 这是加密的key（密钥） 
                    let token = jwt.sign(content, secretOrPrivateKey, {
                        expiresIn: 60 * 60
                    });

                    var result = {
                        "message": "",
                        "status": 200,
                        data: {
                            token: token,
                            user_id: obj.msg.insertId
                        }
                    }
                    res.jsonp(result);
                } else {

                    var result = {
                        "message": "异常",
                        "status": 400
                    }
                    res.jsonp(result);

                }

            } else {

                let content = { userid: user[0].id }; // 要生成token的主题信息
                let secretOrPrivateKey = config.token.secretOrPrivateKey; // 这是加密的key（密钥） 
                let token = jwt.sign(content, secretOrPrivateKey, {
                    expiresIn: 60 * 60 * 24 * 30
                });

                var result = {
                    "message": "",
                    "status": 200,
                    data: {
                        token: token,
                        user_id: user[0].id
                    }
                }
                res.jsonp(result);



            }


        } else {
            var result = {
                "message": "",
                "status": 400
            }
            res.jsonp(result);

        }

    });
})


/**
 * 商品列表
 * @group H5
 * @route POST /wxapi/goods/list
 * @summary 商品列表
 * @param {string} page.formData 
 * @param {string} rows.formData 
 * @param {string} category_id.formData  分类ID
 * @param {string} typeid.formData  活动分类ID
 * @param {string} isrecommend.formData  1推荐
 * @param {string} isshard.formData  2分享
 * @param {string} goods_name.formData  名称
 * @param {string} brandid.formData  品牌ID
 * @param {string} order.formData  default,num,time,price
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 */
router.post('/goods/list', async function (req, res) {

    var shopconfig = myutil.getconfig();

    console.log("cc", req.body);
    var page;
    var rows;
    if (isNaN(req.body.page)) {
        page = 1;
    } else {
        page = +req.body.page;
    }
    if (isNaN(req.body.rows)) {
        rows = 10;
    } else {
        rows = +req.body.rows;
    }
    var first = rows * (page - 1);



    var where = " yoshop_goods.goods_status=1 ";


    if (typeof (req.body.goods_name) != "undefined" && req.body.goods_name != "") {
        where = where + " and yoshop_goods.tags like '%" + req.body.goods_name + "%'";

    }

    var order = " order by yoshop_goods.id desc ";
    if (req.body.order == "num") {
        order = " order by yoshop_goods.sales_actual desc";
    } else if (req.body.order == "time") {
        order = " order by yoshop_goods.create_time desc";
    } else if (req.body.order == "price") {
        order = " order by yoshop_goods_spec.goods_price desc";
    }

    var list = await goods_model.getlist(rows, first, where + " group by yoshop_goods.id ", " left join yoshop_goods_spec on yoshop_goods_spec.goods_id  =yoshop_goods.id ", order, "yoshop_goods.*");
    for (var i = 0; i < list.length; i++) {

        var goods_spec = await goods_spec_model.getinfo("goods_id=" + list[i].id);
        if (goods_spec.length > 0) {
            var goods_price = goods_spec[0].goods_price;
            var line_price = goods_spec[0].line_price;
            list[i].stock_num = goods_spec[0].stock_num;





            list[i].goods_weight = goods_spec[0].goods_weight;
            list[i].spec_value = goods_spec[0].spec_value;
            list[i].goods_specid = goods_spec[0].id;

            list[i].goods_price = parseFloat(goods_spec[0].goods_price * shopconfig.huilv).toFixed(2);
            list[i].line_price = parseFloat(goods_spec[0].line_price * shopconfig.huilv).toFixed(2);

        }


        list[i].create_time = moment(list[i].create_time).format("YYYY-MM-DD HH:mm:ss");


        if (req.body.wxapp_id != undefined && req.body.wxapp_id != "") {


            var goodold = await goods_model.getinfo("goods_name='" + list[i].goods_name + "' and wxapp_id=0");
            if (goodold.length > 0) {
                var goodlist = await db.query("select yoshop_upload_file.file_name from yoshop_goods_image join yoshop_upload_file on yoshop_upload_file.id=yoshop_goods_image.image_id  where yoshop_goods_image.goods_id=" + goodold[0].id
                    + " order by yoshop_goods_image.seq asc ");
                if (goodlist.length > 0) {
                    list[i].imgurl = goodlist[0].file_name;
                }

            }



        } else {
            var goodlist = await db.query("select yoshop_upload_file.file_name from yoshop_goods_image join yoshop_upload_file on yoshop_upload_file.id=yoshop_goods_image.image_id  where yoshop_goods_image.goods_id=" + list[i].id
                + " order by yoshop_goods_image.seq asc ");
            if (goodlist.length > 0) {
                list[i].imgurl = goodlist[0].file_name;
            }

        }




    }
    var count = await goods_model.getinfo(where + " group by yoshop_goods.id ", " join yoshop_goods_spec on yoshop_goods_spec.goods_id  =yoshop_goods.id ", "");
    count = count.length;
    var allcount = parseInt(parseInt(count) / rows) + 1;
    if (count % rows == 0) {
        allcount = allcount - 1;
    }

    res.send({ status: 200, data: list, message: "", allcount: allcount, count: count });

});


/**
 * 商品详情
 * @group H5
 * @route POST /wxapi/goods/info
 * @summary 商品详情
 * @param {string} id.formData 
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 */
router.post('/goods/info', async function (req, res) {



    log.info("goods/info", JSON.stringify(req.body));

    var obj = await goods_model.getinfo("id=" + req.body.id);

    var shopconfig = myutil.getconfig();


    if (obj.length > 0) {
        var info = obj[0];

        var goods_spec = await goods_spec_model.getinfo("goods_id=" + info.id);


        for (var i = 0; i < goods_spec.length; i++) {



            goods_spec[i].stock_num = await getkucun(goods_spec[i].goods_no);

            if (goods_spec[i].imgurl != null && goods_spec[i].imgurl != "") {
                goods_spec[i].imgurl = goods_spec[i].imgurl;
            }
            let goods_price = goods_spec[i].goods_price;
            let line_price = goods_spec[i].line_price



            goods_spec[i].goods_price_chn = parseFloat(goods_price * shopconfig.huilv).toFixed(2);
            goods_spec[i].line_price_chn = parseFloat(line_price * shopconfig.huilv).toFixed(2);


            if (req.body.wxapp_id != undefined && req.body.wxapp_id != "" && req.body.wxapp_id != "0") {
                var apply = await apply_model.getinfo("userid=" + req.body.wxapp_id);
                if (apply.length > 0) {
                    var newbili = parseInt(apply[0].bili) + 100;

                    goods_spec[i].goods_price_chn = parseFloat(parseInt(goods_price * newbili * 0.01) * shopconfig.huilv).toFixed(2);
                    goods_spec[i].line_price_chn = parseFloat(parseInt(line_price * newbili * 0.01) * shopconfig.huilv).toFixed(2);


                    goods_spec[i].goods_price = parseInt(goods_price * newbili * 0.01);
                    goods_spec[i].line_price = parseInt(line_price * newbili * 0.01);


                    var applygoods = await applygoods_model.getinfo("mid=" + req.body.wxapp_id + " and goodid=" + goods_spec[i].goods_id);
                    if (applygoods.length > 0) {
                        newbili = parseInt(applygoods[0].bili) + 100;

                        goods_spec[i].goods_price_chn = parseFloat(parseInt(goods_price * newbili * 0.01) * shopconfig.huilv).toFixed(2);
                        goods_spec[i].line_price_chn = parseFloat(parseInt(line_price * newbili * 0.01) * shopconfig.huilv).toFixed(2);


                        goods_spec[i].goods_price = parseInt(goods_price * newbili * 0.01);
                        goods_spec[i].line_price = parseInt(line_price * newbili * 0.01);

                    }



                }
            }




        }
        // huilv

        info.guigelist = goods_spec;

        if (goods_spec.length > 0) {
            info.stock_num = goods_spec[0].stock_num;
            info.goods_weight = goods_spec[0].goods_weight;
            info.spec_value = goods_spec[0].spec_value;
            info.goods_price_chn = goods_spec[0].goods_price_chn;
            info.line_price_chn = goods_spec[0].line_price_chn;
            info.goods_price = goods_spec[0].goods_price;

            info.line_price = goods_spec[0].line_price;




        }



        var imglist = await db.query("select yoshop_upload_file.file_name,yoshop_upload_file.id  from yoshop_goods_image join yoshop_upload_file on yoshop_upload_file.id=yoshop_goods_image.image_id  where yoshop_goods_image.goods_id=" + info.id
            + " order by yoshop_goods_image.seq asc ");
        for (var i = 0; i < imglist.length; i++) {



        }
        info.imglist = imglist;




        info.nowtime = moment().valueOf();

        var result = {
            "status": "200",
            "message": "success",
            data: info,
            cha: cha
        }
        res.jsonp(result);
    } else {
        var result = {
            "status": "400",
            "message": "success"
        }
        res.jsonp(result);
    }
});



module.exports = router;